package com.cxq.boot.controller;

import com.cxq.boot.dto.CommentCreateDTO;
import com.cxq.boot.dto.CommentDTO;
import com.cxq.boot.dto.ResultDTO;
import com.cxq.boot.enums.CommentTypeEnum;
import com.cxq.boot.exception.CustomizeErrorCode;
import com.cxq.boot.model.Comment;
import com.cxq.boot.model.User;
import com.cxq.boot.service.CommentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class CommentController {
    @Autowired
    private CommentService commentService;

    //根据问题id添加回复
    @PostMapping("/comment")
    @ResponseBody
    public Object post(@RequestBody CommentCreateDTO commentCreateDTO,
                       HttpServletRequest request){

        User user = (User) request.getSession().getAttribute("user");
        if (user == null){
            return ResultDTO.errorOf(CustomizeErrorCode.NO_LOGIN);
        }

        //StringUtils是Commons lang下包装好的工具类
        if (commentCreateDTO == null || StringUtils.isBlank(commentCreateDTO.getContent())){
            return ResultDTO.errorOf(CustomizeErrorCode.COMMENT_IS_EMPTY);
        }

        Comment comment = new Comment();
        comment.setParentId(commentCreateDTO.getParentId());
        comment.setContent(commentCreateDTO.getContent());
        comment.setType(commentCreateDTO.getType());
        comment.setGmtCreate(System.currentTimeMillis());
        comment.setGmtModified(System.currentTimeMillis());
        comment.setCommentator(user.getId());
        comment.setLikeCount(0L);
        //commentMapper.insertSelective(comment);
        commentService.insert(comment,user);

        /*Map<Object,Object> objectMap = new HashMap<>();
        objectMap.put("message","成功");
        return objectMap;*/
        return ResultDTO.okOf();
    }

    //根据问题或回复id获取评论
    @ResponseBody
    @GetMapping("/comment/{id}")
    public ResultDTO<List<CommentDTO>> comments(@PathVariable("id") Long id){
        List<CommentDTO> commentDTOS = commentService.listByQuestionId(id, CommentTypeEnum.COMMENT);
        return ResultDTO.okOf(commentDTOS);
    }
}
